import React, { Component } from 'react'
import { connect } from 'react-redux'
import { sendVCode, updatePhone } from '../../../store/actions'
import '../../../components/form/input.css'
import 'flex.css/dist/data-flex.css'
import './edit-phone.less'
import utils from 'Utils'
import Api from '../../../api'
import Input from 'components/form/input'
import Button from 'components/button/button'
import Toptip from 'components/toptip/toptip'
import { Toast } from 'antd-mobile'
import { validForm, validValue, validField } from 'Utils/lite-validator.js'

@connect(
  state=>state.app
)
class Register extends React.Component {
  constructor () {
    super()
    this.state = {
      sending: false,
      errMsg: '',
      errShow:false,
      errTimmer:null,
      sendBtnText:'发送',
      phone: '',
      code: '',
    }
    this.updateState.bind(this);
    this.sendCode = this.sendCode.bind(this);
  }
  updateState(stateName){
    return e => {
      let v = e.target.value;

      if(!validValue.required(v) || v === this.state[stateName]) return;
      this.setState({[stateName]: v});
    }
  }
  componentWillUnmount(){
    this.state.errTimmer && clearTimeout(this.state.errTimmer);
  }
  showWran(msg){
    this.state.errTimmer && clearTimeout(this.state.errTimmer);
    this.setState({
      errShow: true,
      errMsg: msg,
      errTimmer: setTimeout(()=>{
        this.setState({ errShow: false })
      }, 3000)
    })
  }
  valide(){
    var oFormBox = this.refs.formBoxEditPhone;

    return validForm(oFormBox, {
      'phone': [['required'],['phone','请输入正确的联系方式']],
      'code':[['required'],['length:~6','字符长度过长，请小于6个字符']],
    })
  }
  sendCode(){
    var oFormBox = this.refs.formBoxEditPhone;
    validField(oFormBox, 'phone', [['required'],['phone','请输入正确的联系方式']])
    .then(res=>{
      this.setState({
        sending: true
      })
      Api.sendVCode({
        phone: this.state.phone
      }).then(res=>{
        Toast.info('验证码已发送，请注意查收')
        utils.secondCountDown(60, (s)=>{
          this.setState({sendBtnText: s+'s'})
        }, ()=>{
          this.setState({sendBtnText: '重新发送'});
          this.setState({
            sending: false
          })
        })
      }).catch(err=>{
        this.showWran(err.moreInfo || '验证码发送失败，请重新发送');
        this.setState({
          sending: false
        })
      })
    })
    .catch(err=>{
      err.el.focus();
      err.el.parentElement.classList.add('error');
      this.showWran(err.msg || '输入信息不正确');
    })
  }
  handleSubmit() {
    // 提交 phone 和 code
    var pms = {
      phone: this.state.phone,
      code: this.state.code,
    }
    console.log(pms);
    this.valide().then(res=>{
      this.props.dispatch(updatePhone({
        phone: this.state.phone,
        code: this.state.code
      }))
    }).catch(err=>{
      if(err instanceof Error) throw err;
      err.el.focus();
      err.el.parentElement.classList.add('error');
      this.showWran(err.msg || '输入信息不正确');
    })
  }
  handleIptClick(e){
    e.target.parentElement.classList.remove('error')
  }
  render () {
    return (
      <div ref="formBoxEditPhone" className="edit-phone-frm pt20">

      <div className="view-box">
        <div className="ui-ipt-group bdr-t ipt-new-phone" data-flex="">
          <label className="ui-ipt-label bdr-r" data-flex-box="0">新手机号</label>
          <input type="text" className="ui-ipt" name="phone" placeholder="请输入新手机号码" data-flex-box="1"
            onBlur = { this.updateState('phone') }
            onClick = { this.handleIptClick }
          />
          <div className="btn-send-msg bdr-l tc pt5">
            <a className={`ui-btn bdr primary ${this.state.sending ? 'disabled': ''}`} href="javascript:;"
              onClick={ this.sendCode }
            >{ this.state.sendBtnText }</a>
          </div>
        </div>
        <div className="ui-ipt-group bdr-b ui-form-line" data-flex="">
          <label className="ui-ipt-label bdr-r" data-flex-box="0">校验码</label>
          <input type="text" className="ui-ipt" name="code" placeholder="请输入短信校验码" data-flex-box="1"
            onChange = { this.updateState('code') }
            onClick = { this.handleIptClick }
          />
        </div>
      </div>

        <div className="btn-edit-phone-box p20" style={{paddingTop:'60px'}}>
          <Button
            onClick={this.handleSubmit.bind(this)}
            disabled={!this.state.phone || !this.state.code || this.state.sending}
          >完成</Button>
        </div>

        <Toptip show={this.state.errShow} type="warn">{this.state.errMsg}</Toptip>
    </div>
    )
  }
}

export default connect()(Register);

// <Input type="text" name="company" placeholder="请输入新手机号码" label="新手机号"></Input>
// <Input type="text" name="address" placeholder="请输入短信校验码" label="校验码"></Input>
